package com.betterwood.dragon.service;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.dao.KeywordDao;
import com.betterwood.dragon.entity.Keyword;
import com.betterwood.dragon.entity.Site;

import org.springframework.stereotype.Service;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;

@Service(value = "keywordService")
@RequiredArgsConstructor
public class KeywordService {
    private final KeywordDao keywordDao;
    private final SiteService siteService;

    public Keyword insert(Keyword kw) {
        return keywordDao.save(kw);
    }

    // public Keyword addSiteToKeyword(String keywordId, String siteId) {
    // Keyword kw = keywordDao.getOneById(keywordId);
    // List<Site> sites = keywordSiteDao.addSiteToKeyword(keywordId, siteId);
    // kw.setSitesList(sites);
    // return kw;
    // }

    public List<Keyword> findAll() {
        return keywordDao.findAll();
    }

    public Keyword findById(String id) {
        Keyword kw = keywordDao.getOneById(id);
        return kw;
    }

    public Keyword save(Keyword kw) {
        return keywordDao.save(kw);
    }

    public void addSiteToKeyword(String siteId, String kwId) {

        Keyword kw = findById(kwId);
        if (ObjectUtil.isNull(kw)) {
            return;
        }
        Site site = siteService.findById(siteId);
        if (ObjectUtil.isNull(site)) {
            return;
        }

        List<Site> siteList = kw.getSites();
        List<Keyword> kwList = site.getKeywords();
        if (ObjectUtil.isNull(siteList)) {
            siteList = new ArrayList<Site>();
        }

        boolean kwExist = ObjectUtil.isNull(kwList) ? false
                : kwList.stream().anyMatch(keyword -> keyword.getId().equals(kw.getId()));
        boolean siteExist = ObjectUtil.isNull(kwList) ? false
                : siteList.stream().anyMatch(st -> st.getId().equals(site.getId()));

        if (!(kwExist || siteExist)) {
            siteList.add(site);
            kw.setSites(siteList);
            if (ObjectUtil.isNull(kwList)) {
                kwList = new ArrayList<Keyword>();
            }
            kwList.add(kw);
            site.setKeywords(kwList);
            siteService.save(site);
        }

        save(kw);
    }

}
